/**
 * Created by ayu on 2017/6/28.
 */
let sqlExcute = require ('../utils/DB/MysqlStatement');
Date.prototype.format = function ( format )
{
    let o = {
        "M+": this.getMonth () + 1, //month
        "d+": this.getDate (), //day
        "H+": this.getHours (), //hour
        "m+": this.getMinutes (), //minute
        "s+": this.getSeconds (), //second
        "q+": Math.floor ((this.getMonth () + 3) / 3), //quarter
        "S" : this.getMilliseconds () //millisecond
    };
    if (/(y+)/.test (format))
    {
        format = format.replace (RegExp.$1,
            (this.getFullYear () + "").substr (4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp ("(" + k + ")").test (format))
        {
            format = format.replace (RegExp.$1,
                RegExp.$1.length == 1 ? o[ k ] :
                    ("00" + o[ k ]).substr (("" + o[ k ]).length));
        }
    return format;
};
module.exports = {
    saveJsapiTicket: function ( param )
    {
        let sql = 'REPLACE INTO wechat_jsapi_ticket (id, ticket, expires_in) values(1, ?, ?)';
        let arr = [ param.ticket, param.expires_in * 1000 + Date.now () ];
        sqlExcute.sqlStatement ([ sql, arr ], function ( done )
        {
            let time = (new Date).format('yyyy-MM-dd HH:mm:ss');
            if (done.isSuccess)
            {
                console.log(`[${time}][JsapiTicket] 更新 ${param.ticket}`);
            }
            else
            {
                console.log(`[${time}][JsapiTicket] 更新失败：${param.ticket}`);
            }
        });
    },
    findJsapiTicket: function ( callBack )
    {
        let sql = 'SELECT * FROM wechat_jsapi_ticket where id = ?';
        let arr = [ 1 ];
        sqlExcute.sqlStatement ([ sql, arr ], function ( done )
        {
            if (done.isSuccess)
            {
                callBack ({
                    isSuccess: true,
                    result   : done.result
                });
            }
            else
            {
                callBack ({
                    isSuccess: false
                });
            }
        });
    }
};